package com.dunqi.gpm.cangxi.WeekReport.WeekReport.WeekReportDetail

import android.app.Activity
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.Toast

import com.dunqi.gpm.cangxi.R
import com.dunqi.gpm.cangxi.WPConfig
import com.dunqi.gpm.cangxi.WeekReport.Model.Projects
import com.dunqi.gpm.cangxi.WeekReport.Model.WeekReport
import com.dunqi.gpm.cangxi.WeekReport.Model.WeeklyPlanBean
import com.dunqi.gpm.cangxi.common.base.Data
import com.dunqi.gpm.cangxi.common.util.CommonUtil
import com.dunqi.gpm.cangxi.common.util.FormUtil
import com.dunqi.gpm.cangxi.common.util.RequestBodyUtil
import com.dunqi.gpm.cangxi.home.adapter.PhotoAdapter
import com.dunqi.gpm.cangxi.home.adapter.SpinnerAdapter
import com.dunqi.gpm.cangxi.home.bean.Page
import com.dunqi.gpm.cangxi.home.constance.Constance
import com.foamtrace.photopicker.SelectModel
import com.foamtrace.photopicker.intent.PhotoPickerIntent
import com.foamtrace.photopicker.intent.PhotoPreviewIntent

import com.dunqi.gpm.cangxi.home.constance.Constance.REQUEST_CAMERA_CODE
import com.dunqi.gpm.cangxi.home.constance.Constance.REQUEST_PREVIEW_CODE
import com.foamtrace.photopicker.PhotoPickerActivity
import com.nanchen.compresshelper.CompressHelper
import kotlinx.android.synthetic.main.fragment_week_report.*
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.*


class WeekReportDetailFragment : Fragment(), WeekReportDetailModel.WeekReportResult {
    /**
     * 项目 保存 或 提交 结果
     */
    override fun save(save: Data<*>?) {
        if (save?.resultCode == 1) {
            Toast.makeText(activity, "保存成功", Toast.LENGTH_SHORT).show()
            EventBus.getDefault().post("refresh_weekReportList")
            activity!!.finish()
        } else {
            if (TextUtils.isEmpty(save?.resultMessage))
                Toast.makeText(activity, "保存失败,请重试", Toast.LENGTH_SHORT).show()
            else {
                Toast.makeText(activity, save?.resultMessage, Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 项目的 计划信息
     */
    var plans = ArrayList<WeeklyPlanBean>()

    override fun plans(plans: Page<WeeklyPlanBean>) {
        if (plans.size > 0) {
            this.plans = plans.list
            var list = ArrayList<String?>()
            for (plans in plans.list) {
                list.add("${plans.weeks}")
            }
            setMyPlanSpinner(list)
        } else {

        }
    }

    /**
     * 新增周报告时获取项目列表
     */
    var projects = ArrayList<Projects>()

    override fun projectName(projects: Page<Projects>?) {
        if (projects != null && projects.size > 0) {
            this.projects = projects.list
            var list = ArrayList<String?>()
            for (project in projects.list) {
                list.add(project.projectName)
            }
            setMySpinner(list)
            //获取第一条项目 计划信息
            model?.projectWeeklyReportgetWeeksInfos(this, this.projects[0].projectId)
        } else {

        }
    }

    override fun delete(data: Data<*>?) {
//        {"resultCode":1,"resultMessage":"","data":null,"data2":null,"data3":null,"mapData":{},"success":true,"failed":false}
        if (data?.resultCode == 1) {
            Toast.makeText(activity, "删除成功!", Toast.LENGTH_SHORT).show()
            EventBus.getDefault().post("refresh_weekReportList")
            activity!!.finish()
        } else {
            if (TextUtils.isEmpty(data?.resultMessage))
                Toast.makeText(activity, "删除失败,请重试", Toast.LENGTH_SHORT).show()
            else {
                Toast.makeText(activity, data?.resultMessage, Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun fail(throwable: Throwable?) {

    }

    private var item: WeekReport? = null
    private var mParam2: String? = null

    private var adapter_photo: PhotoAdapter? = null
    internal var list_photo: MutableList<String> = ArrayList()

    private var model: WeekReportDetailModel? = null

    private val photos: ArrayList<String>
        get() {
            val paths = ArrayList<String>()
            for (item in list_photo) {
                if (!TextUtils.isEmpty(item)) {
                    paths.add(item)
                }
            }
            return paths
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            item = arguments!!.getSerializable(ARG_PARAM1) as WeekReport?
            mParam2 = arguments!!.getString(ARG_PARAM2)
        }
        model = WeekReportDetailModel()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_week_report, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setView()
    }

    internal fun setView() {
//        status = null ,0 ： 未审核
//        -1 ：退回重报
//         1：待审核
//        2 ,3 ： 审核中       ??
//        4 ： 审批通过
//        null, -1, 0 ： 可修改，删除
        if (item != null) {//查看 | 修改 \ 删除
            //设置提交时需要的值
            report_check_content.visibility = View.GONE
            project_report_status_container.visibility = View.GONE
            weeklyReportId = "${item?.weekReportId}"
            projectId = "${item?.projectId}"
            weeklyPlanId = "${item?.projectReportWeekly?.weeklyPlanId}"

            setMySpinner(arrayListOf(item?.projectName))
            setMyPlanSpinner(arrayListOf("${item?.projectReportWeekly?.weeks}"))
            project_plan_writer.text = "${item?.createName}"
            project_plan_write_time.text = "${item?.projectReportWeekly?.createTime}"
            project_plan_content.text = "${item?.planContext}"
            project_duty_units.text = item?.orgName
            project_report_content.setText("${item?.reportContext}")
            val pics = item?.projectReportWeekly?.pics
            var status = item?.status
            when (status) {//审核状态控制
                null, 0 -> {
                    project_report_status.text = "未审核"
                }
                -1 -> {
                    project_report_status.text = "退回重报"
                }
                1 -> {
                    project_report_status.text = "待审核"
                    project_report_content.isEnabled = false
                }
                2, 3 -> {
                    project_report_status.text = "审批中"
                    project_report_content.isEnabled = false
                }
                4 -> {//审核通过
                    project_report_status.text = "审批通过"
                    project_report_content.isEnabled = false
                }
            }
            if (status === null || status == 0 || status == -1) {  // 可以编辑 & 删除
                //删除周报告的按钮
                week_report_title.setRightText("操作", {
                    operate()
                })
            } else {
                project_report_content.isEnabled = false
                project_report_remark.isEnabled = false
                //设置两个文本框高度    ----   充分展示内容
                project_plan_content.layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
                project_report_content.layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
                project_report_remark.layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT

            }
            initPhonto(0)
            if (pics != null) {
                for (item in pics) {
                    list_photo.add("${WPConfig.PicBaseUrl}${item?.url}")
                }
            }
            adapter_photo?.notifyDataSetChanged()
        } else {//新建
            week_report_title.setRightText("操作", {
                //                save(false)
                operate()
            })
            project_report_status_rg.visibility = View.GONE
            project_plan_writer_container.visibility = View.GONE
            project_report_status_container.visibility = View.GONE
            untils_hint.visibility = View.GONE
            project_duty_units_container.visibility = View.GONE

            timeSeleter()//时间选择器
            initPhonto(1)
            model?.getProjectName(this)
        }
    }

    fun timeSeleter() {
        val ca = Calendar.getInstance()
        //选择填写时间
        project_plan_write_time.text = String.format("%02d-%02d-%02d", ca.get(Calendar.YEAR), ca.get(Calendar.MONTH) + 1, ca.get(Calendar.DAY_OF_MONTH))
        project_plan_write_time.setOnClickListener {
            val ca = Calendar.getInstance()
            DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                project_plan_write_time.text = String.format("%02d-%02d-%02d", year, month + 1, dayOfMonth)
            }, ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH)).show()
        }
    }

    /**
     * @param  1 可编辑 ,0 不可编辑
     */
    internal fun initPhonto(flag: Int) {
        if (flag == 1)
            list_photo.add("")
        else {
            var status = item?.status
            if (status === null || status == 0 || status == -1) {  // 可以编辑 & 删除
                list_photo.add("")
            }
        }
        adapter_photo = PhotoAdapter(activity, list_photo)
        grid_view.adapter = adapter_photo
        grid_view.setOnItemClickListener { parent, view, position, id ->
            val path = list_photo[position]

            if (TextUtils.isEmpty(path)) {
                //
                val intent = PhotoPickerIntent(activity)
                intent.setSelectModel(SelectModel.MULTI)
                intent.setShowCarema(true) // 是否显示拍照， 默认false
                intent.setMaxTotal(Constance.MAX_PIC) // 最多选择照片数量，默认为9
                val paths = photos
                intent.setSelectedPaths(paths) // 已选中的照片地址， 用于回显选中状态
                // intent.setImageConfig(config);
                startActivityForResult(intent, REQUEST_CAMERA_CODE)
            } else {
                val intent = PhotoPreviewIntent(activity)
                intent.setCurrentItem(position) // 当前选中照片的下标
                val paths = photos
                intent.setPhotoPaths(paths) // 已选中的照片地址
                startActivityForResult(intent, REQUEST_PREVIEW_CODE)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == Constance.REQUEST_CAMERA_CODE) {
            var status = item?.status
            if (item != null && (status === null || status == 0 || status == -1)) {  // 可以编辑 & 删除
                var extra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)
                if (extra === null) {
                    extra = ArrayList()
                }
                list_photo.clear()
                // 选择照片
                list_photo.add("")
                list_photo.addAll(extra)
                adapter_photo?.notifyDataSetChanged()
            }
        }
    }

    companion object {
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private val ARG_PARAM1 = "object"
        private val ARG_PARAM2 = "param2"

        fun newInstance(param1: WeekReport?, param2: String): WeekReportDetailFragment {
            val fragment = WeekReportDetailFragment()
            val args = Bundle()
            args.putSerializable(ARG_PARAM1, param1)
            args.putString(ARG_PARAM2, param2)
            fragment.arguments = args
            return fragment
        }
    }

    var projectName: String? = null
    fun setMySpinner(list: ArrayList<String?>) {
        val toArray = list.toTypedArray()
        var adapter = SpinnerAdapter(activity!!, toArray)
        report_project_name.adapter = adapter
        report_project_name.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(parent: AdapterView<*>, view: View,
                                        position: Int, id: Long) {
                projectName = report_project_name.selectedItem as String
                if (item === null) {
                    for (item in projects) {
                        if (projectName.equals(item.projectName)) {
                            projectId = "${item.projectId}"
                            model?.projectWeeklyReportgetWeeksInfos(this@WeekReportDetailFragment, item.projectId)
                            return
                        }
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
            }
        }
    }

    var planTimes: String? = null
    fun setMyPlanSpinner(list: ArrayList<String?>) {
        val toArray = list.toTypedArray()
        var adapter = SpinnerAdapter(activity!!, toArray)
        project_plan_week.adapter = adapter
        project_plan_week.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(parent: AdapterView<*>, view: View,
                                        position: Int, id: Long) {
                planTimes = project_plan_week.selectedItem as String
                if (item === null) {
                    for (item in plans) {
                        if (planTimes.equals("${item.weeks}")) {
                            weeklyPlanId = "${item.weeklyPlanId}"
                            project_plan_content.setText(item.context)
                            return
                        }
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
            }
        }
    }

    fun operate() {
        val popupMenu = PopupMenu(activity, week_report_title.rightTv)
        var menuId = R.menu.week_report_operate
        popupMenu.getMenuInflater().inflate(menuId, popupMenu.getMenu())
        popupMenu.show()
        popupMenu.setOnMenuItemClickListener({ item_menu ->
            when (item_menu.getItemId()) {
                R.id.week_report_save -> {
                    save(false)
                }
                R.id.week_report_commit -> {
                    save(true)
                }
                R.id.week_report_delete -> {
                    delete(item?.projectReportWeekly?.weeklyReportId)
                }
            }
            false
        })
    }

    fun delete(id: Int?) {
        if (id == 0) {
            Toast.makeText(activity, "请返回列表刷新重试!", Toast.LENGTH_SHORT).show()
            return
        }
        AlertDialog.Builder(activity).setTitle("请确认").setMessage("删除本次报告?").setNegativeButton("返回", null)
                .setPositiveButton("删除") { _, _ -> model?.delete(id, this@WeekReportDetailFragment) }.create().show()
    }

    var projectId: String = ""   //修改 是进入时设置                 新建   Sipner 选择时设置
    var weeklyPlanId: String = "" //修改 是进入时设置                新建   Sipner 选择时设置
    var weeklyReportId: String = "" //修改 是进入时设置
    var uploadFileRemark: String = ""

    /**
     * @param isSubmit 是否为提交（true：提交，false：保存）
     */
    fun save(isSubmit: Boolean) {
        if (TextUtils.isEmpty(projectId)) {
            Toast.makeText(activity, "请选择项目!", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(weeklyPlanId)) {
            Toast.makeText(activity, "请选择计划周次!", Toast.LENGTH_SHORT).show()
            return
        }
        var createTime = project_plan_write_time.text.toString()
        var mContext: String = project_report_content.text.toString()
        var weeks: String = project_plan_week.selectedItem.toString()
        var remark: String = project_report_remark.text.toString()
//          projectId: String = ""
//          weeklyPlanId: String = ""
//          weeklyReportId: String = ""
//
//          uploadFileRemark: String = ""
//          files: String = ""
        val hashMap = HashMap<String, String>()
        hashMap.put("device_id", CommonUtil.getDeviceId())
        hashMap.put("context", mContext)
        hashMap.put("createTime", createTime)
        hashMap.put("projectId", projectId)
        hashMap.put("weeklyPlanId", weeklyPlanId)
        hashMap.put("weeklyReportId", weeklyReportId)
        hashMap.put("weeks", weeks)
        hashMap.put("remark", remark)
        hashMap.put("isSubmit", "${isSubmit}")

        for (photo in photos) {
            if (photo.startsWith("http")) {
                continue
            }
            uploadFileRemark += ",#"
        }
        if (uploadFileRemark.isNotEmpty()) {
            uploadFileRemark = uploadFileRemark.substring(1, uploadFileRemark.length)
        }
        hashMap.put("uploadFileRemark", uploadFileRemark)

        var files: HashMap<String, RequestBody> = FormUtil.AddHeader(hashMap)
        for (photo in photos) {
            if (photo.startsWith("http")) {
                continue
            }
            val file = CompressHelper.getDefault(activity).compressToFile(File(photo))
            files.put("uploadFile\"; filename=\"" + file.name, RequestBodyUtil.get(file))
        }
        model?.save(this, files)
    }
}